import os
import subprocess
try:
    from main import read_shapefile
except:
    import read_shapefile
try:
    from main import database_util
except:
    import database_util
try:
    from main import config_util
except:
    import config_util


def import_shp(file_path):
    table_name, rows_dict, value_list = read_shapefile.Read_shp(file_path)
    is_success = database_util.import_geodata(table_name, rows_dict, value_list)
    if is_success:
        print("success")
    else:
        print("fail")


def import_geotiff(file_path):
    database = config_util.getConfig("postgresql", "database")
    user = config_util.getConfig("postgresql", "user")
    password = config_util.getConfig("postgresql", "password")
    host = config_util.getConfig("postgresql", "host")
    port = config_util.getConfig("postgresql", "port")
    srid = config_util.getConfig("srid", "srid")
    cwd = config_util.getConfig("geotiff", "cwd")
    new_env = os.environ.copy()
    new_env['PGPASSWORD'] = password
    table_name = os.path.basename(file_path).split(".")[0]
    a = "raster2pgsql -s {srid} -C {file_path} {table_name} | psql -h {host} -p {port} -U {user} -d {database}"\
        .format(srid=srid,file_path=file_path,table_name=table_name,host=host,port=port,user=user,database=database)
    result = subprocess.call(a, env=new_env, cwd=cwd, shell=True)
    if result == 0:
        print("success")
    else:
        print("fail")
